// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/functions/lib/aggregates/single_value_accumulator.h>
#include <pollux/exec/container_row_serde.h>

namespace kumo::pollux::functions::aggregate {
    // An accumulator for a single variable-width value (a string, a map, an array
    // or a struct).
    void SingleValueAccumulator::write(
        const BaseVector *vector,
        vector_size_t index,
        HashStringAllocator *allocator) {
        ByteOutputStream stream(allocator);
        if (start_.header == nullptr) {
            start_ = allocator->newWrite(stream);
        } else {
            allocator->extendWrite(start_, stream);
        }

        static const exec::ContainerRowSerdeOptions options{};
        exec::ContainerRowSerde::serialize(*vector, index, stream, options);
        allocator->finishWrite(stream, 0);
    }

    void SingleValueAccumulator::read(const VectorPtr &vector, vector_size_t index)
    const {
        POLLUX_CHECK_NOT_NULL(start_.header);

        HashStringAllocator::InputStream stream(start_.header);
        exec::ContainerRowSerde::deserialize(stream, index, vector.get());
    }

    bool SingleValueAccumulator::hasValue() const {
        return start_.header != nullptr;
    }

    std::optional<int32_t> SingleValueAccumulator::compare(
        const DecodedVector &decoded,
        vector_size_t index,
        CompareFlags compareFlags) const {
        POLLUX_CHECK_NOT_NULL(start_.header);

        HashStringAllocator::InputStream stream(start_.header);
        return exec::ContainerRowSerde::compareWithNulls(
            stream, decoded, index, compareFlags);
    }

    void SingleValueAccumulator::destroy(HashStringAllocator *allocator) {
        if (start_.header != nullptr) {
            allocator->free(start_.header);
            start_.header = nullptr;
        }
    }
} // namespace kumo::pollux::functions::aggregate
